package com.gemme.gemme.wode;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.gemme.gemme.BaseActivity;
import com.gemme.gemme.R;
import com.gemme.gemme.home.BrandBean;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.shequ.BrandFragment;
import com.gemme.gemme.view.GeAddressButton;
import com.gemme.gemme.view.Topview;
import com.jaeger.library.StatusBarUtil;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener;
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import static com.gemme.gemme.gwc.ConfirmOrderActivity.code_dizhi;

//侧滑删除地址
public class AddressNewActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_new);
        initTop();
        initView();

    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {

        SharedPreferences MSP = getSharedPreferences(Constant.MSP, Context.MODE_PRIVATE);

//        MSP.edit().putString(Constant.ACCESS_TOKEN, "").apply();
        String userId = MSP.getString(Constant.UserId, "").trim();
        System.out.println("");
        if(TextUtils.isEmpty(userId))
            return;

        String url = DataManager.BaseUrl_jinlong + "user/paddress/list"+
                "?userId="+ userId
                ;
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
        DataManager.toServer(mContext, url, true, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {

                try {
                    AddressBean addressBean = JSON.parseObject(response, AddressBean.class);
                    List<AddressBean.DataBean> data = addressBean.getData();
                    System.out.println();

                    if(data != null){
                         adapter =  new AddressNewAdapter(data);
                        recyclerView.setAdapter(adapter);


                        System.out.println();
                    }

                }catch (Exception e){

                }
            }
        });
    }

    AddressNewAdapter adapter;
    ArrayList<String> mDataList = new ArrayList<>();
    SwipeRecyclerView recyclerView;
    private void initView() {

        recyclerView = findViewById(R.id.rvResult);

        mDataList.add("1");
        mDataList.add("2");
        mDataList.add("3");
        mDataList.add("4");
       /* DefaultItemDecoration mItemDecoration = new DefaultItemDecoration(ContextCompat.getColor
                (this, R.color.divider_color));
        recyclerView.addItemDecoration(mItemDecoration);*/
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLayoutManager);

//        recyclerView.setOnItemMoveListener(mItemMoveListener);// 监听拖拽，更新UI。
        recyclerView.setItemViewSwipeEnabled(false); // 侧滑删除，默认关闭。
//        recyclerView.setLongPressDragEnabled(false); // 拖拽排序，默认关闭。
        recyclerView.setSwipeMenuCreator(mSwipeMenuCreator); // 菜单创建器。
        recyclerView.setOnItemMenuClickListener(mItemMenuClickListener); // Item的Menu点击。


    }


    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private OnItemMenuClickListener mItemMenuClickListener = new OnItemMenuClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge, int position) {
            menuBridge.closeMenu();


            deleteAddress(position);
        }
    };

    private void deleteAddress(int position) {
        List<AddressBean.DataBean> data = adapter.getData();
        if(position > -1 && data.size() - 1 >= position){

            AddressBean.DataBean dataBean = data.get(position);
            String id = dataBean.getId();
            if(TextUtils.isEmpty(id))
                return;
            SharedPreferences MSP = getSharedPreferences(Constant.MSP, Context.MODE_PRIVATE);

//        MSP.edit().putString(Constant.ACCESS_TOKEN, "").apply();
            String userId = MSP.getString(Constant.UserId, "").trim();
            System.out.println("");
            if(TextUtils.isEmpty(userId))
                return;

            String url = DataManager.BaseUrl_jinlong + "user/paddress/" + id
                    ;
            HashMap<String, String> headMap = new HashMap<>();
            headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
            DataManager.toServer2(mContext, url, DataManager.DELETE_TYPE, "", headMap, new DataManager.GeResponse() {
                @Override
                public void onResponse(String response) {

                    System.out.println("");
                    initData();
                }
            });
        }
    }


    /**
     * 菜单创建器。
     */
    private SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int position) {
            int width = getResources().getDimensionPixelSize(R.dimen.dp_70);

            // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
            // 2. 指定具体的高，比如80;
            // 3. WRAP_CONTENT，自身高度，不推荐;
            int height = ViewGroup.LayoutParams.MATCH_PARENT;


            // 添加右侧的，如果不添加，则右侧不会出现菜单。
            {
                SwipeMenuItem deleteItem = new SwipeMenuItem(getBaseContext()).setBackground(
                        R.drawable.selector_red)
                        .setImage(R.drawable.ic_action_delete)
                        .setText("删除")
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。

                SwipeMenuItem closeItem = new SwipeMenuItem(getBaseContext()).setBackground(
                        R.drawable.selector_purple).setImage(R.drawable.ic_action_close).setWidth(width).setHeight(height);
                swipeRightMenu.addMenuItem(closeItem); // 添加一个按钮到右侧菜单。
            }
        }
    };

    private void initTop() {
//        StatusBarUtil.setColor(this,getResources().getColor(R.color.white_color) );
        StatusBarUtil.setTransparent(this);
//        StatusBarUtil.setTranslucent(this,250);
        Topview topview = findViewById(R.id.topview);
        topview.setContentText("收货地址");

        TextView gebt= findViewById(R.id.address_buttton);
        gebt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getBaseContext(),AddAddressActivity.class));
            }
        });

//        SwipeRefreshLayout
//        SwipeRevealLayout
    }
    public class AddressNewAdapter extends RecyclerView.Adapter<AddressNewAdapter.ViewHolder>{


        private List<AddressBean.DataBean> adapterList;

        public AddressNewAdapter(List<AddressBean.DataBean> adapterList){

            this.adapterList = adapterList;
        }

        public List<AddressBean.DataBean> getData(){
            return adapterList;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
            //adapter_address
            View inflate = LayoutInflater.from(viewGroup.getContext()).
                    inflate(R.layout.adapter_address, null);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            inflate.setLayoutParams(layoutParams);
            return new AddressNewAdapter.ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
           try {
               AddressBean.DataBean dataBean = adapterList.get(position);
               holder.name.setText(dataBean.getAddressee() + dataBean.getMobile());
               holder.address.setText(dataBean.getProvince() +" "+ dataBean.getCity()+" " + dataBean.getCounty()+" " + dataBean.getAddress());

               holder.itemView.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View view) {
                       //todo
                       try {
                           int code = getIntent().getIntExtra("data", -1);
                           if(code == code_dizhi){
                               Intent intent = new Intent();
                               intent.putExtra("data",JSON.toJSONString(dataBean));
                               setResult(1000,intent);
                               /* */
                               finish();
                           }else{
                               /*Intent intent = new Intent(mContext, AddAddressActivity.class);
                               intent.putExtra("data",JSON.toJSONString(dataBean));
                               startActivity(intent);*/
                           }
                       }catch (Exception e){

                       }


                   }
               });

               holder.iv_edit.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View view) {
                       Intent intent = new Intent(mContext, AddAddressActivity.class);
                       intent.putExtra("data",JSON.toJSONString(dataBean));
                       startActivity(intent);
                   }
               });
           }catch (Exception e){

           }
        }

        @Override
        public int getItemCount() {
            return adapterList.size();
        }


        public class ViewHolder extends RecyclerView.ViewHolder {
            TextView name;
            TextView address;
            ImageView iv_edit;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                name = itemView.findViewById(R.id.name);
                address = itemView.findViewById(R.id.address);
                iv_edit = itemView.findViewById(R.id.iv_edit);
            }
        }
    }

}